#!/bin/bash

if [[ $# -ne 2 ]]; then
    echo "The format is as follows:"
    echo "bash falcon-v0.3.0.sh buildpath installpath"
    echo ":param buildpath: 应用构建绝对路径"
    echo ":param installpath: 应用安装绝对路径"
    exit 1
fi

[[ ! "$1" =~ ^/.* || ! -d "$1" || "$1" = "/" ]] &&  echo "请输入正确的构建路径" && exit 1
[[ ! "$2" =~ ^/.* || ! -d "$2" || "$2" = "/" ]] &&  echo "请输入正确的安装路径" && exit 1

get_FALCON_integrate()
{
cnt=1
number=10
while [ $cnt -lt $number ]
do
    set +e
    echo "正在下载FALCON-integrate子模块，时间较长，请耐心等待......"
    git submodule update --init --recursive 
    result_code=$?
    if [ $result_code -ne 0 ];then
        cnt=$[$cnt+1]
    else
        echo "下载FALCON-integrate子模块成功"
        break
    fi
done

if [ $cnt -eq $number ];then
    cd -
    echo "下载FALCON-integrate子模块失败,将dependency/src目录下的离线包拷贝并解压到FALCON-master目录下"
    cp -r dependency/src/FALCON-integrate.tar.gz  $installpath/FALCON-master
    tar -xvf $installpath/FALCON-master/FALCON-integrate.tar.gz -C $installpath/FALCON-master
fi
set -e 
}

buildpath=$1
installpath=$2
[[ "$buildpath" =~ .*/$ ]] && buildpath=${buildpath%/*}
[[ "$installpath" =~ .*/$ ]] && installpath=${installpath%/*}
[[ "$buildpath" == "$installpath" ]] && echo "构建路径与安装路径需为不同路径" && exit 1
yum install -y wget tar environment-modules
set -e  
wget -t 0 -c -P $buildpath https://codeload.github.com/PacificBiosciences/FALCON/zip/refs/heads/master           
unzip -d $installpath $buildpath/master  && rm -rf $buildpath/master
cd $installpath/FALCON-master
git init
git clone https://github.com/PacificBiosciences/FALCON-integrate.git
cd -
cd $installpath/FALCON-master/FALCON-integrate
git checkout develop

get_FALCON_integrate

cd $installpath/FALCON-master/FALCON-integrate

sed -i '12s/gcc/clang/' $(pwd)/FALCON-make/makefile
sed -i '13s/g++/clang++/' $(pwd)/FALCON-make/makefile
   
make init
source env.sh
make config-edit-user
make  all

cat>"$installpath/FALCON-master/FALCON-integrate/fc_env/falcon_modulefiles"<<EOF
#%Module1.0
conflict falcon
variable modfile [file normalize [info script]]
proc getModulefileDir {} {
    variable modfile
    set modfile_path [file dirname \$modfile]
    return \$modfile_path
}
set pwd [getModulefileDir]
set FALCON \$pwd
setenv FALCON \$FALCON
prepend-path PATH \$FALCON/bin
EOF
